import { Button, ConfigProvider, Form, Input, message } from "antd";
import "./Login.css";
import axios from "axios";
import { useHistory } from "react-router-dom";

function Login() {
    const history = useHistory();
    const onFinish = (data) => {
        console.log(data);
        axios.get(`/users?_embed=role&roleState=true&username=${data.username}&password=${data.password}`)
            .then((res) => {
                if (res.data.length === 0)
                    message.error("用户名或密码不正确！");
                else {
                    window.localStorage.setItem("token", JSON.stringify(res.data[0]));
                    history.push("/home");
                }
            });
    };

    return (
        <div className="login-container">
            <div className="login-box-container">
                <ConfigProvider
                    theme={{
                        components: {
                            Form: {
                                labelColor: "white",
                            },
                        },
                    }}
                >
                    <h1>全球新闻发布系统</h1>
                    <Form onFinish={onFinish}>
                        <Form.Item
                            label="用户名"
                            name="username"
                            rules={[
                                {
                                    required: true,
                                    message: "Please input your username!",
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="密码"
                            name="password"
                            rules={[
                                {
                                    required: true,
                                    message: "Please input your password!",
                                },
                            ]}
                        >
                            <Input.Password />
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                登录
                            </Button>
                        </Form.Item>
                    </Form>
                </ConfigProvider>
            </div>
        </div>
    );
}

export default Login;
